import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/shopkeeper',
    name: 'ShopkeeperLayout',
    component: () => import('../views/shopkeeper/Layout.vue'),
    meta: { requiresAuth: true, role: 'shopkeeper' },
    children: [
      {
        path: '',
        redirect: '/shopkeeper/products'
      },
      {
        path: 'products',
        name: 'ShopkeeperProducts',
        component: () => import('../views/shopkeeper/ProductList.vue')
      },
      {
        path: 'products/add',
        name: 'AddProduct',
        component: () => import('../views/shopkeeper/AddProduct.vue')
      },
      {
        path: 'products/edit/:id',
        name: 'EditProduct',
        component: () => import('../views/shopkeeper/EditProduct.vue')
      },
      {
        path: 'orders',
        name: 'ShopkeeperOrders',
        component: () => import('../views/shopkeeper/OrderList.vue')
      }
    ]
  },
  {
    path: '/customer',
    name: 'CustomerLayout',
    component: () => import('../views/customer/Layout.vue'),
    meta: { requiresAuth: true, role: 'customer' },
    children: [
      {
        path: '',
        redirect: '/customer/products'
      },
      {
        path: 'products',
        name: 'CustomerProducts',
        component: () => import('../views/customer/ProductList.vue')
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('../views/customer/Cart.vue')
      },
      {
        path: 'orders',
        name: 'CustomerOrders',
        component: () => import('../views/customer/OrderList.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth) {
    if (!authStore.isAuthenticated) {
      next('/login')
      return
    }
    
    if (to.meta.role && authStore.user?.role !== to.meta.role) {
      // 角色不匹配，重定向到对应角色的首页
      if (authStore.user?.role === 'shopkeeper') {
        next('/shopkeeper/products')
      } else if (authStore.user?.role === 'customer') {
        next('/customer/products')
      } else {
        next('/login')
      }
      return
    }
  }
  
  next()
})

export default router